<template>
  <div class="full-box">
    <div class="footer">
      <Icon icon="ant-design:close-outlined" @click="$emit('close')" />
    </div>
    <iframe ref="iframe" :src="iframeUrl" class="iframe-box"></iframe>
  </div>
</template>

<script setup lang="ts">
  import { nextTick, onMounted, reactive, ref } from 'vue';
  import { PrintBaseUrl, iframeUrl } from './config';
  import { Icon } from '/@/components/Icon';
  import { getDesignInfo } from '/@/api/system/generator/print';
  import { getPrintData } from './hooks/usePrintData';
  import { ApiConfig, InputParamItem } from '/@/components/ApiConfig/src/interface';
  let iframe = ref();
  const props = withDefaults(
    defineProps<{
      id: string;
      requestParamsConfigs: Array<InputParamItem>;
      requestHeaderConfigs: Array<InputParamItem>;
      requestBodyConfigs: Array<InputParamItem>;
    }>(),
    {
      id: '',
    },
  );

  const data: {
    visible: boolean;
    json: string;
    apiConfig: ApiConfig;
  } = reactive({
    visible: false,
    json: '',
    apiConfig: {
      id: '',
      name: '',
      method: '',
      requestParamsConfigs: [], //Query Params
      requestHeaderConfigs: [], //Header
      requestBodyConfigs: [], //Body
    },
  });
  onMounted(async () => {
    try {
      data.visible = true;
      if (props.id) {
        let res = await getDesignInfo(props.id);
        if (res) {
          data.json = res.content;
          data.apiConfig = JSON.parse(res.apiConfig);
          // 转换入参
          data.apiConfig.requestParamsConfigs = props.requestParamsConfigs;
          data.apiConfig.requestHeaderConfigs = props.requestHeaderConfigs;
          data.apiConfig.requestBodyConfigs = props.requestBodyConfigs;
        }
        await init();
      }
    } catch (error) {}
  });
  const init = async () => {
    await nextTick();
    iframe.value.onload = function () {
      sendMessage();
    };
  };
  async function sendMessage() {
    try {
      let printData = await getPrintData(data.apiConfig);
      let info = {
        type: 'preview',
        fields: printData.apiFields,
        subTabulation: printData.subTabulation,
        printData: printData.data,
        json: data.json,
      };
      var wn = iframe.value.contentWindow;
      wn.postMessage(info, PrintBaseUrl);
    } catch (error) {}
  }
</script>

<style scoped>
  .iframe-box {
    width: 100%;
    height: 80vh;
    box-shadow: 0 0 6px 4px #eee;
    max-width: 800px;
    margin: 0 auto;
    border-radius: 10px;
  }

  .full-box {
    position: fixed;
    height: 80vh;
    top: 80px;
    left: calc(50% - 300px);
    z-index: 999;
    width: 800px;
  }

  .footer {
    position: absolute;
    right: 10px;
    top: 10px;
    cursor: pointer;
  }
</style>
